package cn.itcast.hotel;

import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Stats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author mrchen
 * @date 2022/6/17 14:52
 */
public class EsSearchDemo {
    @Test
    public void aggregations2() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.size(0);
        // 设置聚合参数
        source.aggregation(
                AggregationBuilders.stats("statsAgg") // 自定义聚合名称
                        .field("price") // 对价格进行计算
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 获取总的聚合结果
        Aggregations aggregations = response.getAggregations();

        // 根据自定义的聚合名称  获取指定的聚合结果
        Stats statsResult = aggregations.get("statsAgg");
        System.out.println("平均价格: " + statsResult.getAvg());
        System.out.println("最大价格: " + statsResult.getMax());
        System.out.println("最小价格: " + statsResult.getMin());
        System.out.println("求和价格: " + statsResult.getSumAsString());
        System.out.println("总数量: " + statsResult.getCount());

    }
    @Test
    public void aggregations() throws IOException {
        // 按照 品牌进行分组    打印每个分组的名称  和  分组内酒店文档的数量

        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.size(0);

        // 设置聚合参数
        source.aggregation(
                AggregationBuilders.terms("brandAgg") // 自定义聚合名称
                                    .field("brand") // 按照品牌分组
                                    .size(20) // 显示的分组数量
        );
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 获取总的聚合结果
        Aggregations aggregations = response.getAggregations();

        // 根据自定义的聚合名称  获取指定的聚合结果
        Terms termsResult = aggregations.get("brandAgg");

        // 获取结果中的 buckets分组信息
        List<? extends Terms.Bucket> buckets = termsResult.getBuckets();
        // 遍历分组  打印每个分组 的 key 和 文档数量
        for (Terms.Bucket bucket : buckets) {
            System.out.println("=================================================");
            System.out.println("当前分组key值: " + bucket.getKeyAsString());
            System.out.println("当前分组文档数量: " + bucket.getDocCount());
            System.out.println("=================================================");
        }

    }

    @Test
    public void highlight() throws IOException {
        // 1. 创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.matchQuery("all","外滩如家"));

        // 高亮条件设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name"); // 哪个字段高亮
        highlightBuilder.preTags("<span>"); // 前置标签
        highlightBuilder.postTags("</span>"); // 后置标签
        highlightBuilder.requireFieldMatch(false); // 不做搜索条件字段检查
        source.highlighter(highlightBuilder);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    @Test
    public void sortAndPage() throws IOException {
        // 第几页
        int page = 2;
        // 每页显示多少条
        int size = 3;
        // 1. 创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
            // 按照评价 降序 排序
        source.sort("score", SortOrder.DESC);
        //  如果评分一致，按照价格升序排序
        source.sort("price", SortOrder.ASC);
        // 设置分页参数
        source.from((page - 1) * size);
        source.size(size);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }
    /**
     * 查询名称中 包含:  上海外滩   match: name 上海外滩
     *
     *                   价格    range   500 ~ 1000
     *
     *                   排除品牌:
     * @throws IOException
     */
    @Test
    public void bool() throws IOException {
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        // 创建布尔条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 使用布尔条件对象，组合其它基础条件
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "上海外滩");
        boolQuery.must(matchQueryBuilder);

        RangeQueryBuilder priceBuilder = QueryBuilders.rangeQuery("price").gte(500).lt(1000);
        boolQuery.filter(priceBuilder);

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brand", "万怡");
        boolQuery.mustNot(termQueryBuilder);
        // 设置布尔条件
        source.query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }


    @Test
    public void range() throws IOException {
        // 1. 创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.rangeQuery("price").gte(1000).lt(1500));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    /**
     * 查询  品牌: 希尔顿
     */

    @Test
    public void term() throws IOException {
        // 1. 创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();




       source.query(QueryBuilders.termQuery("brand","希尔顿"));



        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }
    /**
     * 分词查询    match   name:  外滩如家
     */
    @Test
    public void match() throws IOException {
        // 1. 创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.matchQuery("name","外滩如家"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    /**
     * 查询全部
     */
    @Test
    public void matchAll() throws IOException {
        // 1. 创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        // 1.1 构建条件
        source.query(QueryBuilders.matchAllQuery());
        // 2. 执行请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 3. 解析结果
        printResult(response);
    }

    private void printResult(SearchResponse response){
        // 3. 解析结果
        SearchHits hits = response.getHits();
        System.out.println("查询到的文档数量: " + hits.getTotalHits().value);
        for (SearchHit hit : hits) {
            String hotelJson = hit.getSourceAsString();
            // 现在得到的文档内容，并没有高亮处理的结果
            HotelDoc hotelDoc = JSON.parseObject(hotelJson, HotelDoc.class);
            // 单独获取高亮处理结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                // 关于文档name字段的高亮处理结果
                HighlightField highlightField = highlightFields.get("name");
                // 将高亮片段拼接成完整的字符串
                String highlightResultStr = StringUtils.join(highlightField.getFragments());
                // 用高亮处理结果 替换之前的name字段内容
                hotelDoc.setName(highlightResultStr);
            }
            System.out.println(hotelDoc);
        }
        // 得到文档列表
//        SearchHit[] searchHits = hits.getHits();
//        // 遍历文档列表
//        for (SearchHit searchHit : searchHits) {
//            String hotelJson = searchHit.getSourceAsString();
//            HotelDoc hotelDoc = JSON.parseObject(hotelJson, HotelDoc.class);
//            // 输出文档内容
//            System.out.println(hotelDoc);
//        }
    }






    RestHighLevelClient client;
    @BeforeEach
    public void init(){
        // 1. 准备好Es的客户端对象
        client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.200.130:9200")
        ));
    }
    @AfterEach
    public void close(){
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
